package com.googlecode.yami;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JOptionPane;

public class Connect {

    public static Connection login(String hst, String usrn, String psw,
	    String defaultHost) {

	Connection conn = null;

	if ((usrn.length() == 0)) {
	    JOptionPane.showMessageDialog(null, "User name field is empty!");
	    return conn = null;
	} else {
	    if (hst.length() == 0) {
		hst = defaultHost;
		JOptionPane.showMessageDialog(null, "Host is empty @"
			+ defaultHost + " used by default.");
	    }

	    try {
		// setting up host userName password and URL
		String userName = usrn;
		String password = psw;
		String url = "jdbc:mysql://" + hst;
		// checking for valid driver
		try {
		    Class.forName("com.mysql.jdbc.Driver").newInstance();
		} catch (Exception e) {
		    JOptionPane.showMessageDialog(null, "An error occured!\n"
			    + e.getMessage() + " is missing!");
		    return conn = null;
		}

		// try to connect with the input parameters
		try {
		    conn = DriverManager.getConnection(url, userName, password);

		    MainWindow.whoIs = userName + "@" + hst;

		    return conn;
		} catch (Exception connError) {
		    JOptionPane.showMessageDialog(null, "Failed to connect: "
			    + userName + "@" + hst + ".\n"
			    + connError.getMessage());
		    return conn = null;
		}
	    } catch (Exception ex) {
		JOptionPane.showMessageDialog(null, ex.getMessage());
		return conn = null;
	    }
	}
    }

    public static ResultSet execSQL(Connection conn, String sql) {
	ResultSet rs = null;
	try {
	    Class.forName("com.mysql.jdbc.Driver").newInstance();
	    Statement s = conn.createStatement();
	    s.executeQuery(sql);
	    rs = s.getResultSet();
	    return rs;
	} catch (SQLException eS) {
	    System.out.println(eS.getMessage());
	    return null;
	} catch (Exception e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	    return null;
	}
    }
}
